package com.guoqi.keepsign.mzt

import android.graphics.Color
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import com.google.gson.Gson
import com.guoqi.keepsign.IPConfig.DEFAULT_TIMEOUT
import com.guoqi.keepsign.IPConfig.DEFUALT_USERAGENT
import com.guoqi.keepsign.R
import com.guoqi.keepsign.base.CommonAdapter
import com.guoqi.keepsign.base.CommonBean
import kotlinx.android.synthetic.main.fm_common.*
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements
import java.util.*


class MztZtUI : AppCompatActivity(), SwipeRefreshLayout.OnRefreshListener {

    val TAG = "MztZTUI"

    private lateinit var url: String
    private lateinit var keyWord: String
    private var mList: ArrayList<CommonBean>? = null
    private var mCommomAdapter: CommonAdapter? = null
    private var mPage: Int? = 1
    private var gm: GridLayoutManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.fm_common)

        initUI()
    }

    private fun initUI() {
        url = intent.getStringExtra("url") ?: ""
        keyWord = intent.getStringExtra("keyWord") ?: ""
        mSwipeRefresh.setColorSchemeColors(Color.rgb(255, 64, 129))
        mSwipeRefresh.setOnRefreshListener(this)
        //lm = LinearLayoutManager(context)
        gm = GridLayoutManager(this, 2)
        mRvCommonList.layoutManager = gm
        mRvCommonList.setHasFixedSize(true)
        mList = ArrayList()
        mRvCommonList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            var lastVisibleItem: Int? = 0
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem!! + 1 == mCommomAdapter?.itemCount) {
                    mCommomAdapter?.changeMoreStatus(mCommomAdapter?.LOAD_MORE!!)
                    mPage = mPage!! + 1
                    getData(mPage)
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val layoutManager = recyclerView?.layoutManager as LinearLayoutManager
                //最后一个可见的ITEM
                lastVisibleItem = layoutManager.findLastVisibleItemPosition()
            }
        })
        if (keyWord.isNotEmpty()) {
            ll_none.visibility = View.VISIBLE
            tv_tip.text = "正在搜索 [$keyWord] ..."
        }
        loading.visibility = View.VISIBLE
        getData(mPage)
    }

    private fun getData(page: Int?) {
        Thread(Runnable {
            try {
                val doc: Document = Jsoup.connect(url + page)
                        .timeout(DEFAULT_TIMEOUT).userAgent(DEFUALT_USERAGENT).get()
                val imgSingle: Elements? = doc.getElementsByClass("lazy")

                imgSingle?.forEach {
                    val mCommonBean = CommonBean(it.attr("alt"), it.attr("data-original"))
                    mList!!.add(mCommonBean!!)
                    Log.e(TAG, Gson().toJson(mCommonBean))
                }
                runOnUiThread {
                    mCommomAdapter?.changeMoreStatus(mCommomAdapter?.PULLUP_LOAD_MORE!!)
                    if (mPage != 1) {
                        mRvCommonList.adapter!!.notifyDataSetChanged()
                    } else {
                        mCommomAdapter = CommonAdapter(this, mList)
                        mRvCommonList.adapter = mCommomAdapter
                    }
                    if (mList!!.isEmpty()) {
                        ll_none.visibility = View.VISIBLE
                        tv_tip.text = "没有找到 [$keyWord] 相关资源"
                    } else {
                        ll_none.visibility = View.GONE
                    }
                    loading.visibility = View.GONE
                }
            } catch (e: Exception) {
                runOnUiThread {
                    loading.visibility = View.GONE
                    mCommomAdapter?.changeMoreStatus(mCommomAdapter?.NO_LOAD_MORE!!)
                }
            }
        }).start()
    }

    override fun onRefresh() {
        mSwipeRefresh.isRefreshing = false
        getData(mPage)
    }

}